package com.rh.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rh.entity.EduSubject;
import com.rh.entity.excel.SubjectData;
import com.rh.service.EduSubjectService;
import com.rh.exception.EducationException;

/**
 * 监听器
 */
public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {
    //因为SubjectExcelListener不能交给Spring管理，不能注入其他对象，可以使用以下方法注入：
    public EduSubjectService subjectService;
    //生成SubjectExcelListener有参无参构造
    public SubjectExcelListener(EduSubjectService subjectService) {
        this.subjectService = subjectService;
    }
    public SubjectExcelListener() { }

    //读取Excel中的内容,一行一行读取
    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if(subjectData==null){ //如果subjectData为空说明没数据，就不用往下走了
            throw new EducationException(20001,"文件数据为空");
        }
        //一行一行读，每次都有两个值，第1个是1级分类，第2个是2级分类
        //先判断1级分类是否重复
        EduSubject oneSubject = this.existOneSubject(subjectService, subjectData.getOneSubjectName());
        //判断1级分类是否重复
        if(oneSubject==null){
            //没有相同的1级分类就添加
            oneSubject=new EduSubject();
            //设置1级分类parent_id
            oneSubject.setParentId("0");
            //设置1级分类名称
            oneSubject.setTitle(subjectData.getOneSubjectName());
            //调用方法保存
            subjectService.save(oneSubject);
        }
        //获取一级分类id值
        String pid=oneSubject.getId();
        //判断2级分类是否重复
        EduSubject twoSubject=existTwoSubject(subjectService,subjectData.getTwoSubjectName(),pid);
        if(twoSubject==null){
            //没有相同的2级分类就添加
            twoSubject=new EduSubject();
            //设置2级分类parent_id-直接获取
            twoSubject.setParentId(pid);
            //设置2级分类名称
            twoSubject.setTitle(subjectData.getTwoSubjectName());
            //调用方法添加
            subjectService.save(twoSubject);
        }
    }
    //判断1级分类不能重复添加
    private EduSubject existOneSubject(EduSubjectService subjectService,String name){
        QueryWrapper<EduSubject>wrapper=new QueryWrapper<>();
        wrapper.eq("title",name);
        //1级分类默认是0
        wrapper.eq("parent_id",0);
        EduSubject oneSubject = subjectService.getOne(wrapper);
        return oneSubject;
    }
        //判断2级分类不能重复添加
        private EduSubject existTwoSubject(EduSubjectService subjectService,String name,String pid){
            QueryWrapper<EduSubject>wrapper=new QueryWrapper<>();
            wrapper.eq("title",name);
            //2级分类id
            wrapper.eq("parent_id",pid);
            EduSubject twoSubject = subjectService.getOne(wrapper);
            return twoSubject;
        }
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
